package com.xuecheng.order.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.service.WxPayService;
import com.xuecheng.api.order.OrderApi;
import com.xuecheng.api.order.model.dto.OrdersDTO;
import com.xuecheng.order.common.utils.UAASecurityUtil;
import com.xuecheng.order.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author itcast
 */
@Slf4j
@RestController
public class OrdersController implements OrderApi {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private WxPayService wxPayService;


    @Override
    @GetMapping("orders/create/{coursePubId}")
    public OrdersDTO createOrModifyOrders(@PathVariable Long coursePubId) {
        String username = UAASecurityUtil.getUser().getUsername();
        OrdersDTO ordersDTO = this.ordersService.createOrModifyOrders(coursePubId, username);
        return ordersDTO;
    }

    @GetMapping("orderPay/wxPay/createPay")
    public Map<String, Object> createPay(String orderNo) {

        String username = UAASecurityUtil.getUser().getUsername();

        Map<String, Object> payResult = this.ordersService.createPay(orderNo, username);

        return payResult;
    }

    /**
     * 微信支付结果通知
     *
     * @return 返回接收消息结果
     */
    @ResponseBody
//    @RequestMapping("order-pay/wx-pay/notify-result")
    @RequestMapping("orderPay/wxPay/notifyPayResult")
    public String notifyPayResult(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());

            String notifyPayResult = this.ordersService.notifyPayResult(xmlResult);
            return WxPayNotifyResponse.success(notifyPayResult);
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }


}
